package wang.chunfan.code.netty.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

/**
 * @version 1.0
 * @Author wangchunfan
 * @Date 2020/6/3 21:47
 **/
public class TimeClientHandle extends ChannelHandlerAdapter {
    private static final Logger LOGGER = Logger.getLogger(TimeClientHandle.class.getName());
    private final ByteBuf firstMessage;

    public TimeClientHandle() {
        byte[] req = "QUERY TIME ORDER".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    /**
     * 客户端与服务端建立连接
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 向服务端发送请求
        ctx.writeAndFlush(firstMessage);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 处理响应
        ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");
        LOGGER.info("Now is : " + body);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 释放资源
        LOGGER.warning("Unexpected exception from downstream :" + cause.getMessage());
        ctx.close();
    }
}
